import time
import sys
import numpy as np
import subprocess
import os

from pathlib import Path

from switchboard import PySbPacket, PySbTx, PySbRx, SbDut

THIS_DIR = Path(__file__).resolve().parent

def main():
    subprocess.run(["xvlog","--sv","my_adder.sv"])
    subprocess.run(["xvlog","--sv","testbench_with_sb.sv"])
    subprocess.run(["xelab","-debug" ,"all" ,"--snapshot" ,"sp1" ,"testbench_with_sb"])
    xsim_process = subprocess.Popen(["xsim", "sp1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    xsim_process.stdin.write("open_vcd\n")
    xsim_process.stdin.write("log_vcd *\n")
    xsim_process.stdin.write("run 20ns\n")
    
    dut = SbDut(cmdline=True)
    dut.input('gen_a_b.sv')
    dut.build()
    
    rx_in_a = PySbRx('from_rtl_to_in_a.q', fresh=True)
    rx_in_b = PySbRx('from_rtl_to_in_b.q', fresh=True)
    # rx_out = PySbRx('data_out.q', fresh=True)
    tx_out = PySbTx('from_out_to_rtl.q', fresh=True)
    
    chip = dut.simulate()
    
    cycle = 3
    valid = 0
    out = 0
    
    while cycle > 0:
        print("hello")
        
        txp = PySbPacket(
            destination=123456789,
            flags=1,
            data=np.arange(1, dtype=np.uint8)
        )
        txp.data[0] = out
        tx_out.send(txp)
        print("send txp:")
        print(txp)
    #for i in range(cycle):
        
        rxp_in_a = rx_in_a.recv() 
        rxp_in_a.data = rxp_in_a.data[:32]
        rxp_in_b = rx_in_b.recv()
        rxp_in_b.data = rxp_in_b.data[:32]
        ready = 1
        in_a_c = rxp_in_a.data[0]
        in_b_c = rxp_in_b.data[0]
        with open("data_in.txt", "w") as file:
            file.write(f"{ready} {in_a_c} {in_b_c}")
            print(f"write to data_in: {ready} {in_a_c} {in_b_c}")
            file.flush()
            file.close()
        print("xsim run 40ns")
        xsim_process.stdin.write("run 40ns\n")
        xsim_process.stdin.flush()
        print("xsim run over")
        
        input("plese enter something to continue")
        #xsim_process.wait()
        # file_path = "/rshome/shixuan.chen/switchboard/combsim/data_out.txt"

        # while True:
        #     try:
        #         with open(file_path, "r") as file:
        #             line = file.readline()
        #             if line:
        #                 res = line.split()
        #                 valid = res[0]
        #                 out = res[1]
        #                 print(f"read from data_out: {valid} {out}")
        #                 break
        #             else:
        #                 print("File is empty, retrying...")
        #                 time.sleep(1)
        #     except FileNotFoundError:
        #         print(f"File {file_path} not found, retrying...")
        #         time.sleep(1)
        #     except Exception as e:
        #         print(f"An error occurred: {e}, retrying...")
        #         time.sleep(1)
        
        
        # Receive from PySbTx
        # rx_out = rx_out.recv()
        # rx_out.data = rx_out.data[:32]
        # valid = rx_out.data[0]
        # out = rx_out.data[0]
        # print("receive RX")
        # print(rx_out)
        # print(f"read from data_out: {valid} {out}")
        
        # Receive from txt
        with open("data_out.txt", "r") as file:
            line = file.readline()
            res = line.split()
            valid = res[0]
            out = res[1]
            print(f"read from data_out: {valid} {out}")
        cycle = cycle - 1
        
    
    xsim_process.stdin.write("close_vcd\n")
    
    xsim_process.stdin.write("quit\n")
    xsim_process.stdin.flush()
    
    xsim_process.communicate() 
    print("xsim end")
    #chip.wait()
    print("verilator end")
    

    

    

main()